package com.dianqu.weather.web.engine.strategy;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;

import com.dianqu.weather.core.model.WeatherInfo;
import com.dianqu.weather.web.engine.EngineStrategyAbstract;

public class EtouchStrategy extends EngineStrategyAbstract {

	private final Logger logger = Logger.getLogger(getClass());
	private static final String WEB_URL = "http://wthrcdn.etouch.cn/weather_mini?city=%s";

	public EtouchStrategy() {
	}

	protected WeatherInfo format(String resource) {
		System.out.println(resource);
		return null;
	}

	protected String getResource(String location) {
		HttpClient client = new DefaultHttpClient();
		try {
			location = URLEncoder.encode(location, "utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		HttpGet get = new HttpGet(String.format(WEB_URL, location));
		InputStream is = null;
		try {
			HttpResponse response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == 200) {
				is = response.getEntity().getContent();
				logger.info("Get the info from etouch. ");
				return IOUtils.toString(is, "gbk");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(is);
			get.releaseConnection();
			client.getConnectionManager().shutdown();
		}
		return null;
	}

}
